#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

// Define a structure to hold the syscall information
struct SyscallInfo {
    int number;
    std::string category;
    std::string name;
    std::string entrypoint;
};

// Function to parse a line and fill a SyscallInfo structure
bool parseLine(const std::string& line, SyscallInfo& info)
{
    // Ignore lines starting with #
    if (line.empty() || line[0] == '#')
    {
        return false;
    }

    std::istringstream stream(line);
    if (!(stream >> info.number >> info.category >> info.name >> info.entrypoint))
    {
        return false; // Parsing failed
    }

    // Check if any number is between 512 and 547
    if (info.number >= 512 && info.number <= 547)
    {
        return false; // Skip this line
    }

    return true; // Parsing succeeded
}

// Function to read syscalls from a file and store them in a vector
std::vector<SyscallInfo> readSyscalls(const std::string& filename)
{
    std::vector<SyscallInfo> syscalls;
    std::ifstream infile(filename);
    std::string line;

    while (std::getline(infile, line))
    {
        SyscallInfo info;
        if (parseLine(line, info))
        {
            syscalls.push_back(info);
        }
    }

    return syscalls;
}

// Function to write syscalls to a header file
void writeSyscalls(const std::string& filename, const std::vector<SyscallInfo>& syscalls)
{
    std::ofstream outfile(filename);

    outfile << "// AUTO GENERATED BY getsyscalls\n";
    outfile << "#ifndef SYSCALL_H\n";
    outfile << "#define SYSCALL_H\n\n";
    outfile << "struct SyscallInfo {\n";
    outfile << "    int number;\n";
    outfile << "    std::string category;\n";
    outfile << "    std::string name;\n";
    outfile << "    std::string entrypoint;\n";
    outfile << "};\n\n";

    outfile << "const std::vector<SyscallInfo> syscalls = {\n";
    for (const auto& info : syscalls)
    {
        outfile << "    {" << info.number << ", \"" << info.category << "\", \"" << info.name << "\", \"" << info.entrypoint << "\"},\n";
    }
    outfile << "};\n\n";

    outfile << "#endif // SYSCALL_H\n";
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " <input_file> <output_file>\n";
        return 1;
    }

    const std::string inputFilename = argv[1];
    const std::string outputFilename = argv[2];

    // Read syscalls from input file
    std::vector<SyscallInfo> syscalls = readSyscalls(inputFilename);

    // Write syscalls to output header file
    writeSyscalls(outputFilename, syscalls);

    std::cout << "Syscalls have been parsed and written to " << outputFilename << std::endl;

    return 0;
}
